package com.example.user.web.controller;

import com.example.user.dto.UserTokenState;
import com.example.user.model.User;
import com.example.user.service.IUserService;
import com.example.user.service.UserTokenService;
import com.example.user.serviceimpl.UserImpl;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.security.SecureRandom;
import java.util.Date;

/**
 * @author lee
 */
@RestController
@RequestMapping(value = "/users")
public class UserController {
    private final Logger LOG = LoggerFactory.getLogger(UserController.class);
    @Qualifier(value = "userImpl")
    @Autowired
    private UserImpl userImpl;
    @Autowired
    DefaultKaptcha defaultKaptcha;

    @Value("${battcn.security.token.expiration-time}")
    private String expireTime;

    @Autowired
    @Qualifier("userTokenService")
    UserTokenService userTokenService;

    @Autowired
    @Qualifier("userService")
    private IUserService panoramicUserService;
    @Autowired
    private AuthenticationManager authenticationManager;

    @RequestMapping(value = "/auth", method = RequestMethod.POST)
    public ResponseEntity<?> createAuthenticationToken(
            @RequestParam("username") String username,
            @RequestParam("password") String password

    ) {

        if (panoramicUserService.getUserInfo(username, new BCryptPasswordEncoder(12, new SecureRandom("leetomlee123".getBytes())).encode(password)) == null) {
            return ResponseEntity.badRequest().body("用户名或密码错误！");

        }
        try {
            final Authentication authentication = authenticationManager.authenticate(
                    new UsernamePasswordAuthenticationToken(username, new BCryptPasswordEncoder(12, new SecureRandom("leetomlee123".getBytes())).encode(password))
            );
            SecurityContextHolder.getContext().setAuthentication(authentication);
            User user = (User) authentication.getPrincipal();
            String jws = userTokenService.generateToken(user.getLoginName(), expireTime);
            return ResponseEntity.ok(new UserTokenState(jws, Integer.valueOf(expireTime)));
        } catch (Exception e) {
            return ResponseEntity.ok(new UserTokenState());
        }
    }

    @PostMapping("/web/register")
    public ResponseEntity addUser(User user, HttpServletRequest request) {
//        String vrifyCode = request.getSession().getAttribute("vrifyCode").toString();
//        if (StringUtils.isEmpty(vrifyCode)) {
//
//            return ResponseEntity.badRequest().body("验证码过期！");
//        }
//        if (!captcha.equalsIgnoreCase(vrifyCode)) {
//            return ResponseEntity.badRequest().body("验证码不正确！");
//        }
//        request.getSession().removeAttribute("vrifyCode");
        if (StringUtils.isEmpty(user)) {
            return new ResponseEntity("参数不能为空", HttpStatus.BAD_REQUEST);
        } else {
            user.setPassword(new BCryptPasswordEncoder(12, new SecureRandom("leetomlee123".getBytes())).encode(user.getPassword()));
            user.setCtime(new Date());
            user.setOperator("web");
            userImpl.addUser(user);
            return new ResponseEntity(HttpStatus.OK);
        }


    }

    @GetMapping(value = "test")
    @PreAuthorize("hasAuthority('admin')")
    public ResponseEntity res() {
        LOG.info("user has admin");
        return new ResponseEntity("xxx", HttpStatus.OK);
    }

    @RequestMapping("/kaptcha")
    public void getCaptcha(HttpServletRequest request, HttpServletResponse response) {
        byte[] captchaChallengeAsJpeg = null;
        ByteArrayOutputStream jpegOutputStream = new ByteArrayOutputStream();
        try {
            //生产验证码字符串并保存到session中
            String createText = defaultKaptcha.createText();
            HttpSession session = request.getSession();
            session.setMaxInactiveInterval(60 * 1);
            session.setAttribute("vrifyCode", createText);
            //使用生产的验证码字符串返回一个BufferedImage对象并转为byte写入到byte数组中
            BufferedImage challenge = defaultKaptcha.createImage(createText);
            ImageIO.write(challenge, "jpg", jpegOutputStream);
        } catch (IllegalArgumentException | IOException e) {
            return;
        }
        captchaChallengeAsJpeg = jpegOutputStream.toByteArray();
        response.setHeader("Cache-Control", "no-store");
        response.setHeader("Pragma", "no-cache");
        response.setDateHeader("Expires", 0);
        response.setContentType("image/jpeg");
        try {
            ServletOutputStream responseOutputStream = response.getOutputStream();
            responseOutputStream.write(captchaChallengeAsJpeg);
            responseOutputStream.flush();
            responseOutputStream.close();

        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}

